#include "details/confdom.hpp"
#include "misc.hpp"

using namespace wheels;
using namespace dm;
using namespace private__;

path :: path( const std::string& path )
{
	std::vector a_str;
	::split( path , '/' , a_str );

	for( auto it = a_str.begin(); it != a_str.end(); ++it ){
		if( !*it.empty() ){
			m_steps__.push_back( *it );
		}
	}
}

bool path :: isRelative()
{
	if( m_steps__.size() > 0 && m_steps__[ 0 ].find( "." ) != std::string::npos ) return true;

	return false;
}

path& path :: operator+( const path& b )
{
	m_steps__ += b.m_steps__;
	return *this;
}

std::string& path :: operator[]( size_t idx )
{
	if( idx < m_steps__.size() ){
		return m_steps__[ idx ];
	}

	throw std::runtime_error( "index overflow" );
}

bool path :: operator()( const std::string& path )
{
	std::vector a_str;
	::split( path , '/' , a_str );

	for( auto it = a_str.begin(); it != a_str.end(); ++it ){
		if( !*it.empty() ){
			m_steps__.push_back( *it );
		}
	}
}

size_t path :: length()
{
	return m_steps__.size();
}

std::string path :: fullPath()
{
	std::string ret;

	for( auto item : m_steps__ ){
		ret += item + "/";
	}

	ret.erase( ret.length() - 1 );
	
	return ret;
}

confDOM :: confDOM():m_current__("./"){}

bool confDOM :: cd( const std::string& path__ )
{
	bool ret = false;

	size_t idx = 0;
	bool find = false;

	path p( path__ );
	p = m_current__ + p;
	
	dm::composite< stDOMItem >   * p_item = this;
	do{
		if( p[ idx ] == "." ){
			continue;
		}else if( p[ idx] == ".." ){
			idx --;
			if( idx <= 0 ){
				return false;
			}
		}
		
		p_item->for_each( [=]( dm:composite< stDOMItem > * item ){
			if( !item ) return;
			auto * pitem = item->get();
			if( pitem->m_name == p[ idx ] ){
				p_item = item;
				find = true;
				return false;
			}

			return true;
		});
		idx ++;
	}while( idx < p.length() && find );

	if( !find ) return ret;

	if( idx >= p.length() ) ret = true;
	m_current__ = p;
	
	return ret;
}

std::string confDOM :: pwd()
{
	return m_current__.fullPath();
}
